from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from cryptography.fernet import Fernet
from django.conf import settings
import base64
import os


class CloudProvider(models.TextChoices):
    """云服务商选择"""
    ALIYUN = 'aliyun', '阿里云'
    TENCENT = 'tencent', '腾讯云'
    HUAWEI = 'huawei', '华为云'
    VOLCENGINE = 'volcengine', '火山引擎'


class CloudAccount(models.Model):
    """云账号配置"""
    name = models.CharField(max_length=100, verbose_name='账号名称')
    provider = models.CharField(
        max_length=20, 
        choices=CloudProvider.choices,
        verbose_name='云服务商'
    )
    access_key = models.CharField(max_length=200, verbose_name='Access Key')
    secret_key = models.TextField(verbose_name='Secret Key')  # 加密存储
    region = models.CharField(max_length=50, default='', blank=True, verbose_name='地域')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    
    class Meta:
        verbose_name = '云账号'
        verbose_name_plural = '云账号'
        unique_together = ['user', 'provider', 'name']
    
    def __str__(self):
        return f'{self.get_provider_display()} - {self.name}'
    
    def _get_fernet_key(self):
        """获取或生成Fernet加密密钥"""
        # 优先从环境变量获取
        key = os.environ.get('FERNET_KEY')
        if key:
            return key.encode()
        
        # 使用Django的SECRET_KEY生成固定的Fernet密钥
        import hashlib
        secret = settings.SECRET_KEY.encode()
        # 使用SHA256生成固定32字节
        key_bytes = hashlib.sha256(secret).digest()
        # 转换为base64编码
        return base64.urlsafe_b64encode(key_bytes)
    
    def save(self, *args, **kwargs):
        # 简单的加密存储（生产环境建议使用更安全的方法）
        if self.secret_key and not self.secret_key.startswith('encrypted:'):
            key = self._get_fernet_key()
            f = Fernet(key)
            self.secret_key = 'encrypted:' + f.encrypt(self.secret_key.encode()).decode()
        super().save(*args, **kwargs)
    
    def get_decrypted_secret_key(self):
        if self.secret_key.startswith('encrypted:'):
            key = self._get_fernet_key()
            f = Fernet(key)
            return f.decrypt(self.secret_key[10:].encode()).decode()
        return self.secret_key


class Domain(models.Model):
    """域名管理"""
    name = models.CharField(max_length=255, verbose_name='域名')
    cloud_account = models.ForeignKey(CloudAccount, on_delete=models.CASCADE, verbose_name='关联云账号')
    zone_id = models.CharField(max_length=100, blank=True, verbose_name='Zone ID')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    last_sync = models.DateTimeField(null=True, blank=True, verbose_name='最后同步时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    
    class Meta:
        verbose_name = '域名'
        verbose_name_plural = '域名'
        unique_together = ['user', 'name']
    
    def __str__(self):
        return self.name


class RecordType(models.TextChoices):
    """DNS记录类型"""
    A = 'A', 'A记录'
    AAAA = 'AAAA', 'AAAA记录'
    CNAME = 'CNAME', 'CNAME记录'
    MX = 'MX', 'MX记录'
    TXT = 'TXT', 'TXT记录'
    NS = 'NS', 'NS记录'
    PTR = 'PTR', 'PTR记录'
    SRV = 'SRV', 'SRV记录'
    CAA = 'CAA', 'CAA记录'


class DNSRecord(models.Model):
    """DNS解析记录"""
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, verbose_name='域名')
    name = models.CharField(max_length=255, verbose_name='主机记录')
    record_type = models.CharField(
        max_length=10,
        choices=RecordType.choices,
        verbose_name='记录类型'
    )
    value = models.TextField(verbose_name='记录值')
    ttl = models.IntegerField(default=600, verbose_name='TTL')
    priority = models.IntegerField(default=0, blank=True, verbose_name='优先级')
    record_id = models.CharField(max_length=100, blank=True, verbose_name='云端记录ID')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    
    class Meta:
        verbose_name = 'DNS记录'
        verbose_name_plural = 'DNS记录'
        unique_together = ['domain', 'name', 'record_type', 'value']
    
    def __str__(self):
        return f'{self.name}.{self.domain.name} ({self.record_type})'


class OperationLog(models.Model):
    """操作日志"""
    ACTION_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('sync', '同步'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name='操作类型')
    resource_type = models.CharField(max_length=50, verbose_name='资源类型')
    resource_id = models.CharField(max_length=100, verbose_name='资源ID')
    description = models.TextField(verbose_name='操作描述')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '操作日志'
        verbose_name_plural = '操作日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.user.username} {self.get_action_display()} {self.resource_type}'
